package cn.iocoder.yudao.module.crm.controller.admin.customerbill;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils;
import cn.iocoder.yudao.module.crm.dal.dataobject.billaccount.BillAccountDO;
import cn.iocoder.yudao.module.crm.service.billaccount.BillAccountService;
import com.alibaba.excel.annotation.ExcelProperty;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.crm.controller.admin.customerbill.vo.*;
import cn.iocoder.yudao.module.crm.dal.dataobject.customerbill.CustomerBillDO;
import cn.iocoder.yudao.module.crm.service.customerbill.CustomerBillService;

@Tag(name = "管理后台 - 客户账单")
@RestController
@RequestMapping("/crm/customer-bill")
@Validated
public class CustomerBillController {

    @Resource
    private CustomerBillService customerBillService;

    @Resource
    private BillAccountService billAccountService;

    @PostMapping("/create")
    @Operation(summary = "创建客户账单")
    @PreAuthorize("@ss.hasPermission('crm:customer-bill:create')")
    public CommonResult<Long> createCustomerBill(@Valid @RequestBody CustomerBillSaveReqVO createReqVO) {
        return success(customerBillService.createCustomerBill(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新客户账单")
    @PreAuthorize("@ss.hasPermission('crm:customer-bill:update')")
    public CommonResult<Boolean> updateCustomerBill(@Valid @RequestBody CustomerBillSaveReqVO updateReqVO) {
        customerBillService.updateCustomerBill(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除客户账单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('crm:customer-bill:delete')")
    public CommonResult<Boolean> deleteCustomerBill(@RequestParam("id") Long id) {
        customerBillService.deleteCustomerBill(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得客户账单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('crm:customer-bill:query')")
    public CommonResult<CustomerBillRespVO> getCustomerBill(@RequestParam("id") Long id) {
        CustomerBillDO customerBill = customerBillService.getCustomerBill(id);
        return success(BeanUtils.toBean(customerBill, CustomerBillRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得客户账单分页")
    @PreAuthorize("@ss.hasPermission('crm:customer-bill:query')")
    public CommonResult<PageResult<CustomerBillRespVO>> getCustomerBillPage(@Valid CustomerBillPageReqVO pageReqVO) {
       // pageReqVO.setStartDate(pageReqVO.getBillDate())
        if(pageReqVO.getBillDate()!=null && pageReqVO.getBillDate().length>0){
            pageReqVO.setStartDate(pageReqVO.getBillDate()[0]);
            if(pageReqVO.getBillDate().length>1)
            pageReqVO.setEndDate(pageReqVO.getBillDate()[1]);
        }


        PageResult<CustomerBillRespVO> pageResult = customerBillService.getCustomerBillPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出客户账单 Excel")
    @PreAuthorize("@ss.hasPermission('crm:customer-bill:export')")
    @ApiAccessLog(operateType = EXPORT)
    public CommonResult exportCustomerBillExcel(@Valid CustomerBillPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {

        if(ObjectUtil.isEmpty(pageReqVO.getCustomerId())){
            return error(new ErrorCode(-1, "请先选择客户再执行导出"));
        }

        if(ArrayUtil.isEmpty(pageReqVO.getBillDate())){
            return error(new ErrorCode(-1, "请选择账单日期再导出"));
        }

        pageReqVO.setStartDate(pageReqVO.getBillDate()[0]);
        pageReqVO.setEndDate(pageReqVO.getBillDate()[1]);
        List<CustomerBillExportVO> list = customerBillService.getCustomerBillList(pageReqVO);
        LocalDate[] billDates = pageReqVO.getBillDate();
        String dateStr = LocalDateTimeUtil.format(billDates[0],"yyyy年MM月");
        String customerName="";
        if(CollectionUtil.isNotEmpty(list)){
            customerName = list.get(0).getCustomerName();
        }
        HashSet<Integer> indexSet = new HashSet<>();
        indexSet.add(9);
        String fileName = "";
        List<List<String>> headerList = getHeaders();
        List<List<String>> headers = new ArrayList<>();
        for (List<String> strings : headerList) {
            List<String> heads = new ArrayList<>();
            fileName = customerName+dateStr+"对账单";
            heads.add(fileName);
            heads.addAll(strings);
            headers.add(heads);
        }
        CustomerBillExportVO sumCell = null;
        try {
            sumCell = ExcelUtils.sumCell(true,8,indexSet,list,CustomerBillExportVO.class);
        } catch (Exception e) {
            //log.error("",e);
        }
        list.add(sumCell);

        BillAccountDO billAccountDO = billAccountService.getDefaultBillAccount();
        if(billAccountDO!=null){
            CustomerBillExportVO row = new CustomerBillExportVO();
            row.setCompanyCode("开户姓名:");
            row.setOrderNo(billAccountDO.getAccountName());
            list.add(row);

            row = new CustomerBillExportVO();
            row.setCompanyCode("开户银行:");
            row.setOrderNo(billAccountDO.getBankName());
            list.add(row);

            row = new CustomerBillExportVO();
            row.setCompanyCode("银行帐号:");
            row.setOrderNo(billAccountDO.getAccountNo());
            list.add(row);
        }

       ExcelUtils.write(response, fileName+".xls", fileName, CustomerBillExportVO.class, list,headers);

        return null;
    }

    public static void main(String[] args) {
        Field[] fields = CustomerBillRespVO.class.getDeclaredFields();;
        for (Field field : fields) {
            ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
            if (annotation != null) {
                //System.out.println("Annotation value: " + JSONUtil.toJsonStr(annotation.value()));
            }
        }
        //Field field = CustomerBillRespVO.class.getFields().getDeclaredField("message");

    }

    private List getHeaders(){
        List<List<String>> headers = new ArrayList<>();
         Field[] fields = CustomerBillRespVO.class.getDeclaredFields();;
        for (Field field : fields) {
            ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
            if (annotation != null) {
                //System.out.println("Annotation value: " + JSONUtil.toJsonStr(annotation.value()));
                headers.add(Arrays.asList(annotation.value()));
            }
        }

        return headers;
    }



}
